package com.leyou.cart.interceptor;

import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.constant.LyConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class UserInfoInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取用户id
        String userIdStr = request.getHeader(LyConstants.AUTH_USER_ID_HEADER_KEY);
        //判空，正常情况下userIdStr一定不会为空。
        if(StringUtils.isEmpty(userIdStr)){
            log.info("【获取用户拦截器】执行失败！获取用户信息为空！");
            //不管用户是否登录，都放行！
            return true;
        }
        //将字符串类型的用户id转成Long类型
        Long userId = Long.valueOf(userIdStr);
        //将用户id放入到一个线程安全的对象中
        UserHolder.setUserId(userId);
        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        UserHolder.removeUserId();
    }

}
